package org.dromara.web.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.RandomUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.web.system.domain.AppMessageRemind;
import org.dromara.web.system.domain.AppOrder;
import org.dromara.web.system.domain.AppProcurementPlan;
import org.dromara.web.system.domain.AppSupplierDetail;
import org.dromara.web.system.domain.bo.AppProcurementPlanBo;
import org.dromara.web.system.domain.vo.AppProcurementPlanVo;
import org.dromara.web.system.mapper.AppMessageRemindMapper;
import org.dromara.web.system.mapper.AppOrderMapper;
import org.dromara.web.system.mapper.AppProcurementPlanMapper;
import org.dromara.web.system.mapper.AppSupplierDetailMapper;
import org.dromara.web.system.service.IAppProcurementPlanService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 采购计划Service业务层处理
 *
 * @author Lion Li
 * @date 2025-09-19
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppProcurementPlanServiceImpl implements IAppProcurementPlanService {

    private final AppProcurementPlanMapper baseMapper;
    private final AppSupplierDetailMapper appSupplierDetailMapper;
    private final AppMessageRemindMapper appMessageRemindMapper;
    private final AppOrderMapper appOrderMapper;

    /**
     * 查询采购计划
     *
     * @param id 主键
     * @return 采购计划
     */
    @Override
    public AppProcurementPlanVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询采购计划列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 采购计划分页列表
     */
    @Override
    public TableDataInfo<AppProcurementPlanVo> queryPageList(AppProcurementPlanBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppProcurementPlan> lqw = buildQueryWrapper(bo);
        Page<AppProcurementPlanVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的采购计划列表
     *
     * @param bo 查询条件
     * @return 采购计划列表
     */
    @Override
    public List<AppProcurementPlanVo> queryList(AppProcurementPlanBo bo) {
        LambdaQueryWrapper<AppProcurementPlan> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppProcurementPlan> buildQueryWrapper(AppProcurementPlanBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AppProcurementPlan> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(AppProcurementPlan::getId);
        lqw.eq(StringUtils.isNotBlank(bo.getPlanCode()), AppProcurementPlan::getPlanCode, bo.getPlanCode());
        lqw.eq(bo.getPlanType() != null, AppProcurementPlan::getPlanType, bo.getPlanType());
        lqw.eq(bo.getQuarterNum() != null, AppProcurementPlan::getQuarterNum, bo.getQuarterNum());
        lqw.eq(bo.getCompanyId() != null, AppProcurementPlan::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), AppProcurementPlan::getCompanyName, bo.getCompanyName());
        lqw.eq(bo.getAuditStatus() != null, AppProcurementPlan::getAuditStatus, bo.getAuditStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getFailReason()), AppProcurementPlan::getFailReason, bo.getFailReason());
        return lqw;
    }

    /**
     * 新增采购计划
     *
     * @param bo 采购计划
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(AppProcurementPlanBo bo) {
        AppProcurementPlan add = MapstructUtils.convert(bo, AppProcurementPlan.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改采购计划
     *
     * @param bo 采购计划
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(AppProcurementPlanBo bo) {
        AppProcurementPlan update = MapstructUtils.convert(bo, AppProcurementPlan.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AppProcurementPlan entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除采购计划信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void updateStatus(String id,String status) {
        //计划审核
        LambdaUpdateWrapper<AppProcurementPlan> appProcurementPlanLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        appProcurementPlanLambdaUpdateWrapper.eq(AppProcurementPlan::getPlanCode, id);
        appProcurementPlanLambdaUpdateWrapper.set(AppProcurementPlan::getAuditStatus, status);
        baseMapper.update(appProcurementPlanLambdaUpdateWrapper);

        //查询计划
        LambdaQueryWrapper<AppProcurementPlan> appProcurementPlanLambdaQueryWrapper = new LambdaQueryWrapper<>();
        appProcurementPlanLambdaQueryWrapper.eq(AppProcurementPlan::getPlanCode, id);
        AppProcurementPlan appProcurementPlan = baseMapper.selectOne(appProcurementPlanLambdaQueryWrapper);
        if (appProcurementPlan!=null){
            //审核成功后。推送消息 ---待下发 推送给对应的供应商
            String supplierId = appProcurementPlan.getSupplierId();
            //查询供应商
            AppSupplierDetail appSupplierDetail = appSupplierDetailMapper.selectById(supplierId);
            Long userId = appSupplierDetail.getUserId();
            //发消息
            AppMessageRemind appMessageRemind = new AppMessageRemind();
            appMessageRemind.setRemindUser(userId);
            appMessageRemind.setPlanCode(appProcurementPlan.getPlanCode());
            appMessageRemind.setIsRead(0L);
            appMessageRemind.setRoleId(2);
            appMessageRemind.setRemark("等待下发！");
            appMessageRemindMapper.insert(appMessageRemind);
            //新建订单 下发状态
            AppOrder appOrder = new AppOrder();
            appOrder.setOrderId(RandomUtils.generateOrderId());
            appOrder.setOrderStatus(0L);
            appOrder.setPlanId(appProcurementPlan.getPlanCode());
            appOrder.setSupplierCode(appSupplierDetail.getSupplierCode());
            appOrder.setTenantId(appProcurementPlan.getTenantId());
            appOrderMapper.insert(appOrder);
        }
    }

    @Override
    public void addCause(String id, String cause) {
        //计划审核
        LambdaUpdateWrapper<AppProcurementPlan> appProcurementPlanLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        appProcurementPlanLambdaUpdateWrapper.eq(AppProcurementPlan::getPlanCode, id);
        appProcurementPlanLambdaUpdateWrapper.set(AppProcurementPlan::getFailReason, cause);
        baseMapper.update(appProcurementPlanLambdaUpdateWrapper);
    }
}
